package Day019_Junit单元测试_NIO.demo6_发消息;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author zhangyan
 * @date 2020/5/12 19:08
 */
public class Test1_Client {
    public static void main(String[] args) throws Exception {
        //SocketChannel类用于连接的客户端，它相当于：Socket

        //获取SocketChannel
        //调用SocketChannel的open()方法打开通道
        SocketChannel sc = SocketChannel.open();

        //调用SocketChannel的实例方法connect(SocketAddress add)连接服务器
        sc.connect(new InetSocketAddress("localhost", 666));

        Scanner s = new Scanner(System.in);
        while (true) {
            // 创建ByteBuffer缓冲数组
            ByteBuffer b1 = ByteBuffer.allocate(1024);
            //键盘录入
            System.out.println("输入要发送的消息:");
            String str = s.nextLine();

            //添加数据到缓冲数组
            byte[] bytes = str.getBytes();
            b1.put(bytes);

            //切换
            b1.flip();

            //把缓冲数组中存储的数据写出
            sc.write(b1);

            if(str.equals("88")){
                break;
            }

            //接收回复消息
            // 创建ByteBuffer缓冲数组
            ByteBuffer b2 = ByteBuffer.allocate(1024);
            sc.read(b2);
            //b2.clear();
            System.out.println("服务端回复:" + new String(b2.array(),0,b2.limit()));
        }
        sc.close();
    }
}

